<template>
  <el-card shadow="hover">
    <el-button type="primary" :icon="Plus" @click="addTradeMark" style="margin: 0 5px;">添加品牌</el-button>
    <!-- el-badge 按钮右上角的角标：el中的徽章组件 -->
    <el-badge :value="trademarkArr.length">
      <el-button @click="exportToExcel" type="default" :icon="UploadFilled">导出数据</el-button>
    </el-badge>
    <!-- 表格内容 :data='全部数据的数组'-->
    <el-table border style="margin: 10px 0;" :data="trademarkArr" id="tableData">
      <!-- type：index 为序号 -->
      <el-table-column label="序号" width='80px' align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px;">
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <!-- row: 具名插槽-->
        <template #="{ row, $index }">
          <el-button type="primary" size="small" :icon="Edit" @click="updateTradeMark(row)"></el-button>
          <el-popconfirm :title="`你确定要删除：${row.tmName}?`" width="250" @confirm="handler(row.id)">
            <template #reference><el-button type="danger" size="small" :icon="Delete"></el-button></template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <!-- current:当前页
             pageSize：总页数
             page-sizes：每页多少条
             layout：组件布局
        -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]"
      layout="prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="sizeHandler"
      @current-change="getTradeMark">
    </el-pagination>
  </el-card>
  <!-- 添加品牌，更新品牌 -->
  <el-dialog v-model="visibeDailog" align-center :title="params.id ? '更新品牌' : '添加品牌'">
    <!-- 表单 -->
    <el-form label-width="100" style="width: 80%;" :model="params" :rules="rules" ref="form">
      <el-form-item label="品牌名称" prop="tmName">
        <el-input placeholder="请你输入品牌的名称" v-model="params.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <!-- 上传文件的组件 -->
        <el-upload class="avatar-uploader" action="/app-dev/admin/product/fileUpload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="params.logoUrl" :src="params.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽传入底部的结构 -->
    <template #footer>
      <el-button @click="visibeDailog = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete, UploadFilled } from '@element-plus/icons-vue';
import { reqTradeMarkList, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from "@/api/product/trademark/trademark";
import type { TradeMarkResonsepe, TrademarkArr, TradeMark } from '@/api/product/trademark/interface/trademark';
import { ElMessage, formContextKey } from 'element-plus';
// 导出数据需要用到的
import * as XLSX from 'xlsx';
//分页器当前页码--默认第一页
const currentPage = ref<number>(1);
//每页需要展示几条数据
const pageSize = ref<number>(3);
// 存储全部数据
const trademarkArr = ref<TrademarkArr>([])
// 存储总共多少条
const total = ref<number>(0);
// 获取form组件实例
const form = ref<any>();
// 储存商品数据
const params = ref<TradeMark>({
  tmName: '',
  logoUrl: ''
})
// 进入页面时获取数据渲染一次
onMounted(() => {
  getTradeMark();
})
// 获取所有数据/更新数据
const getTradeMark = async (val: number = 1) => {
  currentPage.value = val
  const result: TradeMarkResonsepe = await reqTradeMarkList(currentPage.value, pageSize.value);
  total.value = result.total;
  // 储存商品数据
  trademarkArr.value = result.records;
}
// 分页器下拉菜单选项发生变化的时候会触发
const sizeHandler = (val: number) => {
  pageSize.value = val;
  getTradeMark();
}
// 控制添加商品的对话框显示与隐藏
const visibeDailog = ref<boolean>(false);
// 添加品牌，清空对话框内容
const addTradeMark = () => { visibeDailog.value = true; params.value.tmName = ''; params.value.logoUrl = ''; params.value.id = 0 }
//更新品牌的回调
const updateTradeMark = (row: TradeMark) => {
  visibeDailog.value = true;
  params.value.id = row.id;
  params.value.tmName = row.tmName;
  params.value.logoUrl = row.logoUrl;
}
//文件上传组件对应before-upload钩子
const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type === "image/png" || rawFile.type === "image/jpeg" || rawFile.type === "image/gif") {
    if (rawFile.size / 1024 / 1024 < 2) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件不允许超出2M'
      })
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '文件格式不正确'
    })
    return false;
  }

}
// 上传文件这次POST请求成功回调
const handleAvatarSuccess = async (response: any) => {
  // 获取图片上传成功的地址
  params.value.logoUrl = response.data;
  // 校验整个表单项
  await form.value.validate();
}
// 点击添加完成按钮发送请求
const confirm = async () => {
  // 校验整个表单项
  await form.value.validate()
  // 发送请求
  await reqAddOrUpdateTradeMark(params.value);
  // 关闭对话框
  visibeDailog.value = false;
  // 操作成功提示
  ElMessage({
    type: 'success',
    message: '操作成功'
  })
  getTradeMark(params.value.id ? currentPage.value : 1);
}
// 品牌名称规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error('品牌长度至少两位'))
  }
}
// LOGO校验方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value.length) {
    callBack();
  } else {
    callBack(new Error('LOGO图片必须上传'))
  }
}
// 表单校验规则
const rules = {
  tmName: [
    { required: true, trigger: 'blur', validator: validatorTmName }
  ],
  logoUrl: [
    { required: true, validator: validatorLogoUrl }
  ]
}
// 删除商品
const handler = async (id: number) => {
  await reqDeleteTradeMark(id)
  getTradeMark(trademarkArr.value.length > 1 ? currentPage.value : currentPage.value - 1)
}
// 导出表格数据到 Excel
const exportToExcel = () => {
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(trademarkArr.value);
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  XLSX.writeFile(workbook, 'data.xlsx');
}
</script>



<script lang="ts">
name: 'trademark'
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>